﻿using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Grpc.Net.Client;
using Grpc.Service;
using Marchers.Grpc;

namespace Grpc.DemoClient
{
    class Program
    {
        static async Task Main(string[] args)
        {

            // ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            var channel = GrpcChannel.ForAddress("http://10.2.5.90:5000");
            //var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new Greeter.GreeterClient(channel);
            var reply = await client.SayHelloAsync(
                new HelloRequest { Name = "Hello" });
            Console.WriteLine("Greeter 服务返回数据: " + reply.Message);


            var amadeusClient = new Amadeus.AmadeusClient(channel);
            var result = await amadeusClient.HelloAmadeusAsync(new Empty());
            System.Console.WriteLine(result.Message);

            var saveName = await amadeusClient.SaveAmadeusAsync(new SaveAmadeusRequest
            {
                Name = "Marchers Ma"
            });

            System.Console.WriteLine(saveName.Result);

            // test stream

            // var test = amadeusClient.TestStream();   // 基础版本

            // 添加cancel的进阶版
            var cancelTokenSrc = new CancellationTokenSource();
            cancelTokenSrc.CancelAfter(TimeSpan.FromSeconds(2.5));
            var test = amadeusClient.TestStream(cancellationToken: cancelTokenSrc.Token);

            var rand = new Random(DateTime.Now.Millisecond);

            var testResultTask = Task.Run(async () =>
            {
                try
                {
                    await foreach (var resp in test.ResponseStream.ReadAllAsync())
                    {
                        Console.WriteLine(resp.Message);
                    }
                }
                catch (Exception e)
                {
                    System.Console.WriteLine($"Stream canceled. ");
                }
            });

            for (int i = 0; i < 10; i++)
            {
                await test.RequestStream.WriteAsync(new BothTestRequest() { Id = rand.Next(0, 10) });
            }

            await test.RequestStream.CompleteAsync();

            System.Console.WriteLine("message sent");
            System.Console.WriteLine("receive messages:");
            await testResultTask;

            System.Console.WriteLine("Stream test finished");

            Console.ReadKey();
        }
    }
}
